#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : wupeiqi_async
@File : task.py
@Author : Royce
@Time : 2025/7/10 17:52  
@脚本说明 : 
"""

import asyncio
import requests

from util.util import timer

async def download_image(url):
    # 发送网络请求，下载图片（遇到网络下载图片的IO请求，自动化切换到其他任务）

    print("开始下载:", url)
    loop = asyncio.get_running_loop()

    # requests模块默认不支持异步操作,所以就使用线程池来配合实现了.
    future = loop.run_in_executor(None, requests.get, url)
    response = await future
    print('下载完成')

    # 图片保存到本地文件
    file_name = url.rsplit('_')[-1]
    with open(file_name, mode='wb') as file_object:
        file_object.write(response.content)


@timer('ms')
def test():
    url_list = ["https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar_ChsEe12AXQ6A0OH_AAFocMs8nzU621.jpg",
                "https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar_chccsv2BBICAuntfAADjJFd6800429.jpg",
                "https://www3.autoimg.cn/newsdfs/g26/MOB/3c/65/120x90_0_autohomecar_chccP12BFCmAI083AAGq7vKOsGY193.jpg"]
    tasks = [download_image(url) for url in url_list]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))


if __name__ == '_main_':
    test()
